package com.hao.editorview.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;

import com.hao.editorbox.R;
import com.hao.editorview.adapter.EmojiAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by hao on 16/10/19.
 */
public class EmojiFragment  extends Fragment {

    public static final String EMOJI_DELETE = "emoji_delete";

    private Context mContext;
    private EmojiAdapter emojiAdapter;
    private GridView gridView;
    private List<String> listData;


    private OnItemClickListener onItemClickListener;

    public interface OnItemClickListener {
        void onItemClick(AdapterView<?> parent, View view, int position, long id, String content);

        void onDeleteContent();
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContext = getActivity();
        View view = getView();
        if (null == view) {
            view = inflater.inflate(R.layout.emoji_fragment, container, false);
            super.onCreateView(inflater, container, savedInstanceState);
        }
        ViewGroup parent = (ViewGroup) view.getParent();
        if (parent != null) {
            parent.removeView(view);
        }
        gridView = (GridView) view.findViewById(R.id.emoji_grad);
        initAdapter();
        setListener();
        return view;
    }

    private void initAdapter() {
        emojiAdapter = new EmojiAdapter(mContext);
        if (listData == null || listData.size() <= 0)
            listData = new ArrayList<>();
        emojiAdapter.setEmojiList(listData);
        gridView.setAdapter(emojiAdapter);
    }


    public void setData(List<String> list) {
        listData = list;
        listData.add(EMOJI_DELETE);
        if (emojiAdapter != null) {
            emojiAdapter.setEmojiList(list);
            emojiAdapter.notifyDataSetChanged();
        }
    }

    private void setListener() {
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (onItemClickListener == null)
                    return;
                String content = listData.get(position);
                if (content.equals(EMOJI_DELETE))
                    onItemClickListener.onDeleteContent();
                else
                    onItemClickListener.onItemClick(parent, view, position, id, content);
            }
        });
    }
}